﻿using System.Linq;
using System.Web.Routing;
using SlamCms.Web;
using SlamCms.Web.Mvc;

namespace System.Web.Mvc
{
	public static class TagBrowserRouteTableExtensions
	{
		public static TagBrowserRoute MapTagBrowser(this RouteCollection routes, string id)
		{
			return routes.MapTagBrowser(id, id, null);
		}

		public static TagBrowserRoute MapTagBrowser(this RouteCollection routes, string id, string baseUrl, object defaults = null)
		{
			var tagBrowser = TagBrowsers.Browsers.Where(x => x.Id == id).FirstOrDefault();

			if (tagBrowser == null)
			{
				tagBrowser = new TagBrowser() { Id = id };
				TagBrowsers.Browsers.Add(tagBrowser);
			}

			// {TagBrowserId}/{tag1}/{tag2}/{page} page number acts as a tag, it is resolved by model binder
			var tagBrowserRoute = new TagBrowserRoute(baseUrl.TrimEnd('/') + "/{*tags}");
			tagBrowserRoute.AddDefaults(defaults);
			tagBrowserRoute.AddConstraint("tagBrowserId", new TagBrowserRouteConstraint());
			routes.Add(baseUrl, tagBrowserRoute);

			tagBrowser.RouteValues = tagBrowserRoute.Defaults;

			tagBrowser.RouteValues["TagBrowserId"] = id;

			if (!tagBrowser.RouteValues.ContainsKey("controller"))
				tagBrowser.RouteValues["controller"] = id;

			if (!tagBrowser.RouteValues.ContainsKey("action"))
				tagBrowser.RouteValues["action"] = "Index";

			return tagBrowserRoute;
		}
	}
}
